package com.cool.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域 及 Cookie传递 配置
 *
 * @author Jiangmanman
 * @date 2020/07/23
 */
@Configuration
@Slf4j
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter(){

        log.info("/**************************************************/");
        log.info("/*********************允许跨域**********************/");
        log.info("/**************************************************/");

        //添加Cors配置信息
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //允许的域,不要写*，否则cookie就无法使用了
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setMaxAge(3600L);
        //是否发送Cookie信息
        corsConfiguration.setAllowCredentials(true);
        //允许空的头信息
        corsConfiguration.addAllowedMethod("*");
        //添加映射路径,拦截一切请求
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);

        return new CorsFilter(urlBasedCorsConfigurationSource);

    }
}
